/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ro.peoplecentric.ctc.faces.i18n;

import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.faces.context.FacesContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.web.jsf.FacesContextUtils;

/**
 * Spring resource bundle.
 *
 * @author pguzun
 */
public class SpringResourceBundle extends ResourceBundle {

    private MessageSource messageSource;
    private static final Object SYNC = "";

    public SpringResourceBundle() {
    }

    @Override
    protected Object handleGetObject(String key) {
        if (messageSource == null) {
            synchronized (SYNC) {
                ApplicationContext appContext = getApplicationContext();
                messageSource = (MessageSource) appContext.getBean("messageSource");
            }
        }

        FacesContext fContext = FacesContext.getCurrentInstance();
        Locale locale = fContext.getViewRoot().getLocale();
        return messageSource.getMessage(key, null, locale);
    }

    private ApplicationContext getApplicationContext() {
        FacesContext fc = FacesContext.getCurrentInstance();
        return FacesContextUtils.getWebApplicationContext(fc);
    }

    @Override
    public Enumeration<String> getKeys() {
        return null;
    }
}
